package com.cwt_taxi_xa.protocol.voice;

import android.util.Log;

public class ResendTask {
    private String TAG = "ResendTask";
    private Thread resendThread;

    private byte[] buffer;

    private int resendCount = 4;

    private int sleepTime = 2 * 1000;

    public void saveCache(byte[] buffer){
        if(buffer != null && buffer.length > 0){
            this.buffer = new byte[buffer.length];
            if(buffer != null){
                System.arraycopy(buffer,0,this.buffer,0,buffer.length);
            }
        }
    }

    public synchronized void startResend(){
        if(resendThread == null || resendThread.isInterrupted()){
            resendThread = new Thread(runnable);
            resendThread.start();
        }
    }

    public synchronized void cancelResend(){
        if(resendThread != null){
            try {
                resendThread.interrupt();
            } catch (Exception e) {
                e.printStackTrace();
            }

            resendThread = null;
        }
        Log.e(TAG,"发送声耕指令-------重发任务打断");
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            int index = 0;
            while (!Thread.currentThread().isInterrupted() && index < resendCount){
                try {
                    Thread.sleep(sleepTime);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG,"发送声耕指令-------重发");
                            VoiceTool.sendSerialDataResend(buffer);
                        }
                    }).start();
                    //VoiceTool.sendSerialData7Test(buffer);//分包发送
                    index++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
            Log.e(TAG,"发送声耕指令-------重发任务结束");
        }
    };
}
